import { getOrderSettlementField } from '@/api/order'
import { ref } from 'vue'

export interface FinishOrderRender {
  title: string
  customFieldTxt: Array<CustomFieldTxt>
  customFieldRate: Array<CustomFieldRate>
  customFieldFile: Array<CustomFieldFile>
}

export interface CustomFieldTxt {
  name: string
  type: number
  val: string
  id: string
}

export interface CustomFieldRate {
  name: string
  type: number
  val: number
  id: string
}

export interface CustomFieldFile {
  name: string
  type: number
  val: Array<string>
  id: string
}

export interface ArrowClickParam {
  infoIndex: number
  fieldIndex: number
  direction: 'left' | 'right'
}

export const useGetFinishOrderInfo = () => {
  const finishOrderInfos = ref<Array<FinishOrderRender>>([])
  const getOrderFinishInfoLoading = ref(false)
  const getOrderFinishInfo = async (id: string) => {
    if (id) {
      getOrderFinishInfoLoading.value = true
      const res = await getOrderSettlementField(id)
      getOrderFinishInfoLoading.value = false
      if (res.data.success) {
        finishOrderInfos.value = res.data.data.rows.map((finishOrderInfo) => {
          const customFieldTxt: Array<CustomFieldTxt> = []
          const customFieldRate: Array<CustomFieldRate> = []
          const customFieldFile: Array<CustomFieldFile> = []
          finishOrderInfo.fieldVals.forEach((field) => {
            if ([1, 2, 3, 4].includes(field.type)) {
              customFieldTxt.push({
                name: field.name,
                type: field.type,
                id: field.id,
                val: field.optVos.map((item) => item.optValue).join('，'),
              })
            }

            if (field.type === 8) {
              customFieldRate.push({
                name: field.name,
                type: field.type,
                val: field.optVos
                  .map((item) => item.optValue)
                  .reduce((pre, cur) => Number(pre) + Number(cur), 0),
                id: field.id,
              })
            }

            if ([5, 6, 7].includes(field.type)) {
              customFieldFile.push({
                name: field.name,
                type: field.type,
                val: field.optVos.map((item) => item.optValue),
                id: field.id,
              })
            }
          })

          return {
            title: finishOrderInfo.template,
            customFieldTxt,
            customFieldRate,
            customFieldFile,
          }
        })
      } else {
        throw new Error(res.data.message)
      }
    }
  }

  return {
    finishOrderInfos,
    getOrderFinishInfoLoading,
    getOrderFinishInfo,
  }
}
